//
//  TopicViewController.m
//  BuffetNews
//
//  Created by 李荃荃 on 14-11-4.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "TopicViewController.h"
#import "NetHandler.h"
#import "FirstTableViewCell.h"
#import "UIImageView+WebCache.h"
#import "SecondTableViewCell.h"
#import "AutoScrollView.h"
#import "OneImageTableViewCell.h"
#import "NoneImageTableViewCell.h"
#import "ThreeImageTableViewCell.h"
#import "CommentViewController.h"
#import "NightModel.h"
#import "WebColor.h"
#import "Reachability.h"
#import <SystemConfiguration/SystemConfiguration.h>

@interface TopicViewController ()<UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) NSMutableDictionary *bigDic; //  存储解析完的大字典
@property (nonatomic, retain) NSMutableArray *galleryArr;  //  存储上面的大图片新闻
@property (nonatomic, retain) NSMutableArray *articlesArr; //  存储相关新闻
@property (nonatomic, retain) AutoScrollView *autoScrollView;
@end

@implementation TopicViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    self.view.backgroundColor = [UIColor redColor];
//    [self LoadingView];
    [self ConnectData];
   
}
//  加载数据
- (void)ConnectData
{
    
    BOOL reachable = [[Reachability reachabilityForInternetConnection] isReachable];
    
    if (!reachable) {
        UIAlertView *alertView = [[[UIAlertView alloc] initWithTitle:@"请检查您的网络连接状态" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil] autorelease];
        [alertView show];
        
        
        
    } else {

    
    
    //  将传进来的数组中topic的pk值取出来，然后进行字符串拼接
    NSString *idNumber = [[self.receiveDic objectForKey:@"topic"] objectForKey:@"pk"];

    
    NSString *string1 = @"http://iphone.myzaker.com/zaker/topic.php?_appid=iphone&_bsize=640_1136&_dev=iPhone%2C7.1.2";
    NSString *string2 = [NSString stringWithFormat:@"&_v=4.4.5&_version=4.52&app_id=11599&topic_id=%@", idNumber];
    NSString *string = [string1 stringByAppendingString:string2];
    
    [NetHandler networkWithURL:string comaletion:^(id result) {
        [self LoadingView];//  加载视图
        self.bigDic = [result objectForKey:@"data"];
        self.galleryArr = [[result objectForKey:@"data"] objectForKey:@"gallery"];
        self.articlesArr = [[result objectForKey:@"data"] objectForKey:@"articles"];
    }];
        
    }
}

-(BOOL)isReachableViaWWAN
{
    return ([[Reachability reachabilityForLocalWiFi] currentReachabilityStatus] != NotReachable);
}


- (void)LoadingView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    if ([NightModel shareInstance].open == 1) {
        self.tableView.backgroundColor = [WebColor dimGray];
    } else {
        self.tableView.backgroundColor = [UIColor whiteColor];
    }
    [self.view addSubview:self.tableView];
    [_tableView release];
    
    //  返回首页按钮
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    button.frame = CGRectMake(10, self.view.frame.size.height - 30, 40, 30);
    [button setBackgroundImage:[UIImage imageNamed:@"btn_home.png"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
}
//  返回首页
- (void)buttonClicked:(UIButton *)button
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10; //  设置
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [self.articlesArr count] + 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSString *str = [[self.galleryArr lastObject] objectForKey:@"abstract"];
    if (section == 0) {
        if (str != nil) {
            return 3;
        } else {
            return 2;
        }
    } else {
    return [[self.articlesArr[section - 1] objectForKey:@"list"] count];
    }
}


- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{   if (section == 0) {
    return nil;
    } else {
    return [self.articlesArr[section - 1] objectForKey:@"title"];
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //   用来判断是否有简介这一项，控制第一个section中cell的个数
    NSString *str = [[self.galleryArr lastObject] objectForKey:@"abstract"];
    
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"pool"];
    FirstTableViewCell *cell1 = [tableView dequeueReusableCellWithIdentifier:@"pool1"];
    SecondTableViewCell *cell2 = [tableView dequeueReusableCellWithIdentifier:@"pool2"];
    NoneImageTableViewCell *cell3 = [tableView dequeueReusableCellWithIdentifier:@"pool3"];
    OneImageTableViewCell *cell4 = [tableView dequeueReusableCellWithIdentifier:@"pool4"];
    ThreeImageTableViewCell *cell5 = [tableView dequeueReusableCellWithIdentifier:@"pool5"];
    
    //  判断夜间模式
    if ([NightModel shareInstance].open == 1) {
        cell.backgroundColor = [WebColor dimGray];
        cell1.backgroundColor = [WebColor dimGray];
        cell2.backgroundColor = [WebColor dimGray];
        cell3.backgroundColor = [WebColor dimGray];
        cell4.backgroundColor = [WebColor dimGray];
        cell5.backgroundColor = [WebColor dimGray];
    } else {
        cell.backgroundColor = [UIColor whiteColor];
        cell1.backgroundColor = [UIColor whiteColor];
        cell2.backgroundColor = [UIColor whiteColor];
        cell3.backgroundColor = [UIColor whiteColor];
        cell4.backgroundColor = [UIColor whiteColor];
        cell5.backgroundColor = [UIColor whiteColor];
    }
    
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"pool"] autorelease];
    }
    
    if (indexPath.row == 0 && indexPath.section == 0) {
        if (cell1 == nil) {
            cell1 = [[[FirstTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"pool1"] autorelease];
        }
//        NSString *imgString = [[[self.bigDic objectForKey:@"block_info"] objectForKey:@"diy"] objectForKey:@"bgimage_url"];
//        [cell1.imgView sd_setImageWithURL:[NSURL URLWithString:imgString]];
        cell1.imgView.image = [UIImage imageNamed:@"worldTopic.png"];

        return cell1;
    } else if (indexPath.row == 1 && indexPath.section == 0) {
        
        if (cell2 == nil) {
            cell2 = [[[SecondTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"pool2"] autorelease];
        }
        
        //  取出self.galleryArr中的照片的URL地址
        self.autoScrollView = [[AutoScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 200)];
        
        NSMutableArray *imgArr = [NSMutableArray array];
        NSMutableArray *titleArr = [NSMutableArray array];
        for (NSDictionary *dic in self.galleryArr) {
            NSString *imgUrl = [dic objectForKey:@"promotion_img"];
            NSString *title = [dic objectForKey:@"title"];
            [imgArr addObject:imgUrl];
            [titleArr addObject:title];
        }
 
        //  滚动相册
        [self.autoScrollView setImageUrls:imgArr];
        self.autoScrollView.titleArray = titleArr;
        [self.autoScrollView setTitleArray:titleArr];

        [cell2 addSubview:self.autoScrollView];        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
        [self.autoScrollView.scrollView addGestureRecognizer:tap];

        [cell2 addSubview:self.autoScrollView];

        [tap release];
        [_autoScrollView release];

        return cell2;
    } else if (str != nil && indexPath.row == 2 && indexPath.section == 0) {
        //   头条新闻介绍
        cell.textLabel.text = [self.bigDic objectForKey:@"abstract"];
        cell.textLabel.numberOfLines = 0;
        cell.textLabel.font = [UIFont systemFontOfSize:15];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    } else {
        //  每个section中的新闻
        NSMutableDictionary *arr = self.articlesArr[indexPath.section - 1];
        NSMutableArray *listArr = [arr objectForKey:@"list"];
        NSDictionary *dic = listArr[indexPath.row];
        NSMutableArray *thumbnail_mediasArr = [[dic objectForKey:@"article"] objectForKey:@"thumbnail_medias"];
        NSInteger count = [thumbnail_mediasArr count];
        if (thumbnail_mediasArr == nil) {
            if (cell3 == nil) {
                cell3 = [[[NoneImageTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"pool3"] autorelease];
            }
            //  没有图片
            cell3.titleLabel.text = [[dic objectForKey:@"article"] objectForKey:@"title"];
            cell3.autherLabel.text = [[dic objectForKey:@"article"] objectForKey:@"auther_name"];
            return cell3;
        } else if (count == 1) {
            if (cell4 == nil) {
                
                cell4 = [[[OneImageTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"pool4"] autorelease];
            }
            //  一张图片
            cell4.titleLabel.text = [[dic objectForKey:@"article"] objectForKey:@"title"];
            cell4.authorLabel.text = [[dic objectForKey:@"article"] objectForKey:@"auther_name"];
            NSString *imgUrl = [[thumbnail_mediasArr lastObject] objectForKey:@"url"];
            [cell4.imgView sd_setImageWithURL:[NSURL URLWithString:imgUrl]];
            return cell4;
        } else if (count > 1) {
            if (cell5 == nil) {
                cell5 = [[[ThreeImageTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"pool5"] autorelease];
            }
            cell5.titleLabel.text = [[dic objectForKey:@"article"] objectForKey:@"title"];
            cell5.authorLabel.text = [[dic objectForKey:@"article"] objectForKey:@"auther_name"];
            if (count > 2) {
                //   多于3张图片时，取数组中前三张图片
                NSString *str1 = [thumbnail_mediasArr[0] objectForKey:@"url"];
                NSString *str2 = [thumbnail_mediasArr[1] objectForKey:@"url"];
                NSString *str3 = [thumbnail_mediasArr[2] objectForKey:@"url"];
                [cell5.imgView1 sd_setImageWithURL:[NSURL URLWithString:str1]];
                [cell5.imgView2 sd_setImageWithURL:[NSURL URLWithString:str2]];
                [cell5.imgView3 sd_setImageWithURL:[NSURL URLWithString:str3]];
            } else {
                //   两张图片
                NSString *str1 = [thumbnail_mediasArr[0] objectForKey:@"url"];
                NSString *str2 = [thumbnail_mediasArr[1] objectForKey:@"url"];
                [cell5.imgView1 sd_setImageWithURL:[NSURL URLWithString:str1]];
                [cell5.imgView2 sd_setImageWithURL:[NSURL URLWithString:str2]];
            }
            
            return cell5;
        }
    return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section > 0) {
        //  推出三级页面，
        NSMutableDictionary *arr = self.articlesArr[indexPath.section - 1];
        NSMutableArray *listArr = [arr objectForKey:@"list"];
        NSDictionary *dic = listArr[indexPath.row];
        NSString *string = [[dic objectForKey:@"article"] objectForKey:@"weburl"];
        CommentViewController *commentVC = [[CommentViewController alloc] init];
        commentVC.webString = string;
        [commentVC setModalTransitionStyle:UIModalTransitionStyleCoverVertical];
        [self presentViewController:commentVC animated:YES completion:^{
            
        }];
    }
}

- (void)tapAction:(UITapGestureRecognizer *)tap
{
    NSInteger pageNo = [self.autoScrollView pageNo];
    NSString *string = [[self.galleryArr[pageNo] objectForKey:@"article"] objectForKey:@"weburl"];
    CommentViewController *commentVC = [[CommentViewController alloc] init];
    commentVC.webString = string;
    [commentVC setModalTransitionStyle:UIModalTransitionStyleCoverVertical];
    [self presentViewController:commentVC animated:YES completion:^{
        
    }];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0 && indexPath.section == 0) {
        return 60;
    } else if (indexPath.row == 1 && indexPath.section == 0) {
        return 200;
    } else if (indexPath.row == 2 && indexPath.section == 0){
        
        NSString *str = [self.bigDic objectForKey:@"abstract"];
        CGRect rect = [str boundingRectWithSize:CGSizeMake(500, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:15]} context:nil];
        return rect.size.height + 40;
    } else {
        //  根据每条新闻中照片的数量判断该cell的高度
        NSMutableDictionary *arr = self.articlesArr[indexPath.section - 1];
        NSMutableArray *listArr = [arr objectForKey:@"list"];
        NSDictionary *dic = listArr[indexPath.row];
        NSMutableArray *thumbnail_mediasArr = [[dic objectForKey:@"article"] objectForKey:@"thumbnail_medias"];
        NSInteger count = [thumbnail_mediasArr count];
        if (count == 0) {
        //  如果是没有照片，则返回60的高度
            return 60;
        } else {
        
        return 120;
        }
    }
}




- (void)dealloc
{
    [_tableView release];
    [_receiveDic release];
    [_bigDic release];
    [_galleryArr release];
    [_articlesArr release];
    [_autoScrollView release];
    [super dealloc];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
